import os
import json

from basic_component_related_management.models import *
from control.models.User import User
from unit.models import *
from literature.models import *
from django.db import IntegrityError, transaction


intermediate_data_dir = "./files/ddb_dataV1/Intermediate_data"
meta_data_dir = "./files/ddb_dataV1/meta_data"


def init_ddb_component():
    component_file = os.path.join(meta_data_dir, "substance_meta_data.jsonl")
    with open(component_file, "r", encoding="utf-8") as f:
        component_data = f.readlines()

    DDB_entity = Attribute.objects.filter(
        main_dataIndex="system_ddb_id").first()
    DSI_entity = Attribute.objects.filter(
        main_dataIndex="system_dsi_id").first()
    alias_entity = Attribute.objects.filter(
        main_dataIndex="system_other_name").first()
    component_group_list = []
    component_group_dict = {}
    component_entity_list = []
    component_entity_group_list = []
    component_attribute_value_list = []
    user_name = "admin"
    num = 0
    for line in component_data:
        component_item = {}
        line_json = json.loads(line)
        CAR = line_json["CAR"]
        DSI = json.dumps(line_json["DSI"])
        ExtId_DDB = json.dumps(line_json["ExtId_DDB"])
        Formula = line_json["Formula"]
        InChiKey = line_json["InChiKey"]
        Smiles = line_json["Smiles"]
        SubstanceClass_D = line_json["SubstanceClass_D"]
        SubstanceClass_E = line_json["SubstanceClass_E"]
        Synonym = line_json["Synonym"]
        Synonym_D = line_json["Synonym_D"]
        Synonym_E = line_json["Synonym_E"]
        SystematicName_D = line_json["SystematicName_D"]
        SystematicName_E = line_json["SystematicName_E"]
        # SubstanceGroupName_E = line_json["SubstanceGroupName_E"]
        # SubstanceGroupName_D = line_json["SubstanceGroupName_D"]
        # group不要了！！
        # print("CAR:",type(CAR))
        # print("DSI:",type(DSI))
        # print("ExtId_DDB:",type(ExtId_DDB))

        # 先处理Component
        component_item["name"] = SystematicName_D
        component_item["name_en"] = SystematicName_E
        component_item["molecular_formula"] = Formula
        component_item["cas_number"] = CAR
        component_item["smiles_number"] = Smiles
        component_item["inchi_number"] = InChiKey
        component_item["description"] = "ddb数据初始化"
        component_item["create_person"] = user_name
        component_item["modify_person"] = user_name
        component_entity = ComponentIdentifier(**component_item)
        component_entity_list.append(component_entity)

        # 处理DSI
        component_dsi_entity = ComponentAttributeValue(
            componentidentifier=component_entity, attribute=DSI_entity, main_value=DSI)
        component_attribute_value_list.append(component_dsi_entity)

        # 处理ExtId_DDB
        component_ddb_id_entity = ComponentAttributeValue(
            componentidentifier=component_entity, attribute=DDB_entity, main_value=ExtId_DDB)
        component_attribute_value_list.append(component_ddb_id_entity)
        # 处理别名
        all_alias = []
        all_alias.extend(Synonym)
        all_alias.extend(Synonym_D)
        all_alias.extend(Synonym_E)
        component_alias_entity = ComponentAttributeValue(
            componentidentifier=component_entity, attribute=alias_entity, main_value=json.dumps(all_alias))
        component_attribute_value_list.append(component_alias_entity)
        # 先处理ComponentGroup,同时遍历SubstanceClass_D，SubstanceClass_E
        for i in range(len(SubstanceClass_D)):
            component_group = SubstanceClass_D[i]
            component_group_en = SubstanceClass_E[i]
            if component_group in component_group_dict:
                component_group_entity = component_group_dict[component_group]
            else:
                component_group_item = {}
                component_group_item["name"] = component_group
                component_group_item["name_en"] = component_group_en
                component_group_item["description"] = "ddb数据初始化"
                component_group_item["create_person"] = user_name
                component_group_item["modify_person"] = user_name
                component_group_entity = ComponentGroup(**component_group_item)
                component_group_dict[component_group] = component_group_entity
                component_group_list.append(component_group_entity)
            component_entity_group = ComponentIdeComponentGroupMap(
                componentidentifier=component_entity, componentGroup=component_group_entity)
            component_entity_group_list.append(component_entity_group)
        # num += 1
        # if num >=20:
        #     break

    with transaction.atomic():
        ComponentGroup.objects.bulk_create(component_group_list)
        ComponentIdentifier.objects.bulk_create(component_entity_list)
        ComponentIdeComponentGroupMap.objects.bulk_create(
            component_entity_group_list)
        ComponentAttributeValue.objects.bulk_create(
            component_attribute_value_list)

    print("init_ddb_component Done!")


def init_other_left_data():
    other_data_file = os.path.join(meta_data_dir, "other_info_data.json")
    with open(other_data_file, "r", encoding="utf-8") as f:
        other_data = json.load(f)
    user_name = "admin"

    # 新建单位内容
    dimension_entity = Dimension.objects.filter(
        dimension_id="D_Dimensionless").first()
    basic_unit = Unit.objects.filter(
        dimension=dimension_entity, is_system=True).first()

    # 所有单位装进去（加后缀）
    unit_create_list = []
    unit_symbol_list = []
    unit_conversion_list = []
    SiUnit_set = other_data["SiUnit_set"]
    Unit_set = other_data["Unit_set"]
    all_unit_set = set(SiUnit_set).union(set(Unit_set))
    for ddb_unit in all_unit_set:
        unit_item = {}
        unit_item["unit_name"] = "{}(ddb)".format(ddb_unit)
        unit_item["unit_name_en"] = "{}(ddb)".format(ddb_unit)
        unit_item["symbol"] = "{}(ddb)".format(ddb_unit)
        unit_item["dimension"] = dimension_entity
        unit_item["comment"] = "ddb系统初始化"
        unit_item["create_person"] = user_name
        unit_item["modify_person"] = user_name
        unit = Unit(**unit_item)
        unit_create_list.append(unit)
        unit_symbol_item = {}
        unit_symbol_item["symbol"] = "{}(ddb)".format(ddb_unit)
        unit_symbol_item["root_unit"] = unit
        unit_symbol_item["comment"] = "系统创建单位符号(ddb)"
        unit_symbol_item["create_person"] = user_name
        unit_symbol_item["modify_person"] = user_name
        unit_symbol_item["is_system"] = True
        unit_symbol = UnitSymbol(**unit_symbol_item)
        unit_symbol_list.append(unit_symbol)
        unit_conversion_item = {}
        unit_conversion_item["base_unit"] = basic_unit
        unit_conversion_item["target_unit"] = unit
        unit_conversion_item["factor"] = 1.0
        unit_conversion_item["offset"] = 0.0
        unit_conversion_item["create_person"] = user_name
        unit_conversion_item["modify_person"] = user_name
        unit_conversion = UnitConversion(**unit_conversion_item)
        unit_conversion_list.append(unit_conversion)

    # 新建一个叫做ddb的量

    quantity_entity = Quantity(
        quantity_name="ddb量",
        quantity_name_en="ddb",
        quantity_type="NORMAL",
        dimension=dimension_entity,
        description="ddb数据初始化",
        create_person=user_name,
        modify_person=user_name
    )
    quantity_unit_list = []
    for unit in unit_create_list:
        quantity_unit_list.append(
            QuantityUnitMap(quantity=quantity_entity, unit=unit))

    # 定义一个ddb物性类别
    property_group = PropertyGroup(
        name="ddb物性类别",
        name_en="ddb",
        description="ddb数据初始化",
        create_person=user_name,
        modify_person=user_name,
    )

    # 物性内容
    property_entity_list = []
    proptype_data = other_data["PropType_PropSubType_dict"]
    for key, value in proptype_data.items():
        Property1 = Property(
            name="{}(ddb)".format(key),
            name_en="{}(ddb)".format(key),
            property_group=property_group,
            quantity=quantity_entity,
            common_used=True,
            create_person=user_name,
            modify_person=user_name,
        )
        property_entity_list.append(Property1)
        for subkey in value:
            Property2 = Property(
                name="{};{}(ddb)".format(key, subkey),
                name_en="{};{}(ddb)".format(key, subkey),
                property_group=property_group,
                quantity=quantity_entity,
                common_used=True,
                create_person=user_name,
                modify_person=user_name,
            )
            property_entity_list.append(Property2)
    # 相态内容
    phase_entity_list = []
    phase_data = other_data["Phase_set"]
    for phase_name in phase_data:
        Phase1 = Phase(
            name="{}(ddb)".format(phase_name),
            name_en="{}(ddb)".format(phase_name),
            description="ddb数据初始化",
            create_person=user_name,
            modify_person=user_name,
        )
        phase_entity_list.append(Phase1)

    with transaction.atomic():
        Unit.objects.bulk_create(unit_create_list)
        UnitSymbol.objects.bulk_create(unit_symbol_list)
        UnitConversion.objects.bulk_create(unit_conversion_list)
        Quantity.objects.bulk_create([quantity_entity])
        QuantityUnitMap.objects.bulk_create(quantity_unit_list)
        PropertyGroup.objects.bulk_create([property_group])
        Property.objects.bulk_create(property_entity_list)
        Phase.objects.bulk_create(phase_entity_list)
    print("init_other_left_data Done!")


def init_literature_data():
    bibliography_file = os.path.join(
        meta_data_dir, "bibliography_meta_data.jsonl")
    with open(bibliography_file, "r", encoding="utf-8") as f:
        bibliography_data = f.readlines()
    # 创建一个superadmin，密码是superadmin1234
    user_entity = User.objects.filter(user_account="superadmin").first()
    if user_entity is None:
        user_entity = User.objects.create(
            user_account="superadmin",
            user_name="superadmin",
            password="C6IDQGUT42vVUX0neDCF2TB2kD42tBWwp4AGqp3DenmkTYI9urFbhJomuOMcI25De98AjQJPBT07AUW5oQdYeHfeQKr/uhR6OABnKu+/uof5viBguKPdDqkc/znPMjADdt66dxVi/yeur8EahDaUCvhssdB4HkJLxteCLGlEDZ/AJe1BiTBCgyN+7ZLCEjxXD4lKbI5mT9oWEQ+Pd1rE7fY/jmuDh6Nnz2YO7/0WvQA39KESBVzrVQ5bmEVSnUNkQqfzR8DkylHQ54swmNGXFog9xd7q0gjd2VrsBfE6qD4y+iJThQlALLh1f9QdVthAcuepLUKW+PI/mmyllQTufw=="
        )
    language_entity = Language.objects.filter(name="unknown").first()
    status_entity = LiteratureStatusType.objects.filter(
        name="Available").first()
    liter_type_entity = LiteratureType.objects.filter(
        name="Unspecified").first()
    # 开始创建文献
    literature_entity_list = []
    author_entity_list = []
    literature_ID_author_dict = {}
    literature_ID_literature_dict = {}
    for bibliography_item1 in bibliography_data:
        literature_item = {}
        other_json = {}
        comment_content = ""
        bibliography_item = json.loads(bibliography_item1)

        if bibliography_item["Authors"] != "":
            author1 = Author(
                name=bibliography_item["Authors"],
                creator=user_entity,
                last_editor=user_entity,
                reviewer = user_entity,
            )
            author_entity_list.append(author1)
            literature_ID_author_dict[bibliography_item["ID"]] = author1
        literature_item["language"] = language_entity
        literature_item["status"] = status_entity
        literature_item["liter_type"] = liter_type_entity
        
        
        literature_item["title"] = bibliography_item["Title_E"]
        if bibliography_item["Title"] != "":
            other_json["DDB_Title"] = bibliography_item["Title"]
        if bibliography_item["Title_D"] != "":
            other_json["DDB_Title_D"] = bibliography_item["Title_D"]
        if bibliography_item["ID"] != "":
            other_json["DDB_ID"] = bibliography_item["ID"]
            comment_content += "DDB_ID:{}\n".format(bibliography_item["ID"])
        if bibliography_item["Journal"] != "":
            other_json["DDB_Journal"] = bibliography_item["Journal"]
            comment_content += "DDB_Journal:{}\n".format(
                bibliography_item["Journal"])
        if bibliography_item["Coden"] != "":
            other_json["DDB_Coden"] = bibliography_item["Coden"]
            comment_content += "DDB_Coden:{}\n".format(
                bibliography_item["Coden"])
        if bibliography_item["Volume"] != "":
            other_json["DDB_Volume"] = bibliography_item["Volume"]
            comment_content += "DDB_Volume:{}\n".format(
                bibliography_item["Volume"])
        if bibliography_item["Pages"] != "":
            other_json["DDB_Pages"] = bibliography_item["Pages"]
            comment_content += "DDB_Pages:{}\n".format(
                bibliography_item["Pages"])
        if bibliography_item["Year"] != "":
            other_json["DDB_Year"] = bibliography_item["Year"]
            comment_content += "DDB_Year:{}\n".format(
                bibliography_item["Year"])
        if bibliography_item["ISBN"] != "":
            other_json["DDB_ISBN"] = bibliography_item["ISBN"]
            comment_content += "DDB_ISBN:{}\n".format(
                bibliography_item["ISBN"])
        if bibliography_item["Collection"] != "":
            other_json["DDB_Collection"] = bibliography_item["Collection"]
            comment_content += "DDB_Collection:{}\n".format(
                bibliography_item["Collection"])
        if bibliography_item["DocType"] != "":
            other_json["DDB_DocType"] = bibliography_item["DocType"]
            comment_content += "DDB_DocType:{}\n".format(
                bibliography_item["DocType"])
        if bibliography_item["BibLanguage"] != "":
            other_json["DDB_BibLanguage"] = bibliography_item["BibLanguage"]
            comment_content += "DDB_BibLanguage:{}\n".format(
                bibliography_item["BibLanguage"])
        if bibliography_item["DOI"] != "":
            literature_item["DOI"] = bibliography_item["DOI"]
        if bibliography_item["Issue"] != "":
            other_json["DDB_Issue"] = bibliography_item["Issue"]
            comment_content += "DDB_Issue:{}\n".format(
                bibliography_item["Issue"])
        if bibliography_item["Abstract"] != "":
            literature_item["abstract"] = bibliography_item["Abstract"]
        if bibliography_item["CorporateSource"] != "":
            other_json["DDB_CorporateSource"] = bibliography_item["CorporateSource"]
            comment_content += "DDB_CorporateSource:{}\n".format(
                bibliography_item["CorporateSource"])
        if bibliography_item["Editor"] != "":
            other_json["DDB_Editor"] = bibliography_item["Editor"]
            comment_content += "DDB_Editor:{}\n".format(
                bibliography_item["Editor"])
        if bibliography_item["MonographTitle"] != "":
            other_json["DDB_MonographTitle"] = bibliography_item["MonographTitle"]
            comment_content += "DDB_MonographTitle:{}\n".format(
                bibliography_item["MonographTitle"])
        if bibliography_item["Publisher"] != "":
            other_json["DDB_Publisher"] = bibliography_item["Publisher"]
            comment_content += "DDB_Publisher:{}\n".format(
                bibliography_item["Publisher"])
        literature_item["extra_properties"] = other_json
        literature_item["comment"] = comment_content
        literature_item["creator"] = user_entity
        literature_item["last_editor"] = user_entity
        literature_item["reviewer"] = user_entity
        literature1 = Literature(
            **literature_item
        )
        literature_ID_literature_dict[bibliography_item["ID"]] = literature1
        literature_entity_list.append(literature1)
    with transaction.atomic():
        Author.objects.bulk_create(author_entity_list)
        Literature.objects.bulk_create(literature_entity_list)
        for key, value in literature_ID_author_dict.items():
            literature_ID_literature_dict[key].authors.set([value])

    print("init_literature_data Done!")


def init_ddb_dataV1():
    # init_ddb_component()
    # init_other_left_data()
    # init_literature_data()

    print("init_ddb_dataV1 Done!")
